// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// To make sure we can uniquely identify each screenshot tab, add an id as a
// query param to the url that displays the screenshot.
// Note: It's OK that this is a global variable (and not in localStorage),
// because the event page will stay open as long as any screenshot tabs are
// open.
var id = 100;
var cnt = 0;
var baseurl = "http://chrome.tisa.tk";
//baseurl = "http://127.0.0.6:8086";
var Capturer = {
    canvas: document.createElement("canvas"),
	//截取全屏时连接页面后获取实际分辨率的长度
    yPos: 0,
	//截取全屏是连接页面后获取浏览器的长度
	yHeight: 0,
	//浏览器实际页面的宽,高
    scrollHeight: 0,
    scrollWidth: 0,
	//操作类型
	type: "single",
	
	//向content.js发送一个信息为fetchPageSize,获取页面大小
    fetchPageSize: function (tabId){
        var self = this;
        // chrome.tabs.sendMessage(tabId, {act: 'fetchPageSize'}, self.onResponseVisibleSize); 
		var port = chrome.tabs.connect(tabId);
		console.log("ok");
		port.postMessage({act: 'fetchPageSize'});
		port.onMessage.addListener(function(message){
			self.onResponseVisibleSize(message.pagesize);
		});
    },
    //向content.js发送请求滚动页面	
    scrollPage: function(tabId, x, y){
        var self = this;
        //chrome.tabs.sendMessage(tabId, {act: 'scrollPage', x: x, y: y}, self.onScrollDone);
		var port = chrome.tabs.connect(tabId);
		port.postMessage({act: 'scrollPage', x: x, y: y});
		port.onMessage.addListener(function(message){
			self.onScrollDone(message.pagesize);
		});
    },
	
	//滚动10ms后调用截屏函数
    onScrollDone: function(resMsg) {
        setTimeout(function(){
            Capturer.captureVisibleBlock();
        }, 10)
    },
	
	//开始捕获页面信息
    startCapture: function(){
        // scroll to top
        
        this.yPos = 0;
        this.scrollPage(this.tabId, 0, -1 * this.scrollHeight);
        // self.postImg();
    },
	
	//将从content返还的页面信息存到Capturer中去
    onResponseVisibleSize: function (pageSize) {
		console.log(pageSize);
		var PageType = Capturer.type; 
        Capturer.scrollWidth = pageSize.scrollWidth;
        Capturer.scrollHeight = pageSize.scrollHeight;
        Capturer.clientWidth = pageSize.clientWidth;
        Capturer.clientHeight = pageSize.clientHeight;
		
		Capturer.canvas.height = PageType == "single" ? pageSize.clientHeight:pageSize.scrollHeight;

        Capturer.startCapture();
    },
	
	//绘制可见区域块的网页内容
    captureVisibleBlock: function (w, h){
        var self = this;
		var width = w || self.clientWidth;
        var height = h || self.clientHeight;
		
        chrome.tabs.captureVisibleTab(null, function(img) {
            var blockImg = new Image();
			blockImg.src = img;
			//console.log(blockImg.width);
			//console.log(blockImg.height);

			width = blockImg.width-17;
			height = blockImg.height;
			if(cnt == 0){
				Capturer.canvas.width = blockImg.width-17;
				cnt++;
			}
			
			//判断是否浏览器分辨率与电脑分辨率是否一致
			
            var canvas = self.canvas;
			var PageType = Capturer.type;
			//var ctx = canvas.getContext("2d");
			
			if(PageType == "single"){
				blockImg.onload = function() {
					canvas.height = blockImg.height;
					ctx = canvas.getContext("2d");
					ctx.drawImage(blockImg, 0, 0, width, height, 0, 0, width, height);
					Capturer.postImg();
				}
			}
			else if(PageType == "whole"){
				//canvas.height = (canvas.height/Capturer.clientHeight+ canvas.height%Capturer.height == 0?0:1)*blockImg.height;
				//console.log(canvas.height,(canvas.height/Capturer.clientHeight+ canvas.height%Capturer.height == 0?0:1)*blockImg.height);
				ctx = canvas.getContext("2d");
				//判断是否已经滚动到了底部
				if (Capturer.yHeight + Capturer.clientHeight >= Capturer.scrollHeight) {
					blockImg.onload = function() {
						var y = Capturer.clientHeight - Capturer.scrollHeight % Capturer.clientHeight;
						ctx.drawImage(blockImg, 0, 0, width, height, 0, self.yPos - y, width, height);
						Capturer.postImg(); 
					};
				} else {
					blockImg.onload = function() {
						ctx.drawImage(blockImg, 0, 0, width, height, 0, Capturer.yPos, width, height);
						Capturer.yPos += blockImg.height;
						Capturer.yHeight += Capturer.clientHeight;
						console.log(Capturer.yPos,Capturer.yHeight);
						//网页没有到达底部还需要继续滚动
						self.scrollPage(self.tabId, 0, Capturer.clientHeight);
					};
				}
			}/* else{
				chrome.tabs.create({url: "http://chrome.tisa.tk"},function(tab){});
			} */
        });

    },
	//将已经绘制好的canvas传递给前台js
    postImg: function () {
        var canvas = Capturer.canvas;
        var screenshotUrl = canvas.toDataURL();
		//将扩展安装目录内的文件的相对路径转为FQDN URL全域名。
        var viewTabUrl = chrome.extension.getURL('Note.html?id=' + id++);
        chrome.tabs.update({url: viewTabUrl}, function(tab) {
            var targetId = tab.id;

            var addSnapshotImageToTab = function(tabId, changedProps) {
                // We are waiting for the tab we opened to finish loading.
                // Check that the the tab's id matches the tab we opened,
                // and that the tab is done loading.
				//等待打开页面加载完成，检查页面的id是否与我们打开的页面相匹配。
                if (tabId != targetId || changedProps.status != "complete")
                    return;

                // Passing the above test means this is the event we were waiting for.
                // There is nothing we need to do for future onUpdated events, so we
                // use removeListner to stop geting called when onUpdated events fire.
				//当标签页进行更新时我们不需要监听
                //chrome.tabs.onUpdated.removeListener(addSnapshotImageToTab);

                // Look through all views to find the window which will display
                // the screenshot.  The url of the tab which will display the
                // screenshot includes a query parameter with a unique id, which
                // ensures that exactly one view will have the matching URL.
				//在所有的视图中我们寻找需要显示的那个视图，确保本视图的url时独一无二的
                var views = chrome.extension.getViews();
                for (var i = 0; i < views.length; i++) {
                    var view = views[i];
                    if (view.location.href == viewTabUrl) {
                        view.setScreenshotUrl(screenshotUrl,Capturer.scrollWidth-17,Capturer.canvas.height);
                        view.setBaseUrl(baseurl);
						break;
                    }
                }
            };
            chrome.tabs.onUpdated.addListener(addSnapshotImageToTab);
        });
    }
};

//开始进行截图操作
function takeScreenshot() {
    var tabId = chrome.tabs.getSelected(function(tab){
        Capturer.tabWin = window;
        Capturer.tabId = tab.id;
        Capturer.fetchPageSize(tab.id);
    });
}

//popup.html点击监听事件
function buttonClick(PageType){
	Capturer.type = PageType;
	console.log("准备开始进入截屏函数: "+PageType);
	if(PageType == "collect")
		chrome.tabs.create({url: baseurl},function(tab){});
	else
		takeScreenshot();
}
